package com.atguigu.flink.socket;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

/**
 * Created by 黄凯 on 2023/6/11 0011 20:57
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 */
public class SocketServer2 {


    public static void main(String[] args) throws Exception {

        try (ServerSocket server = new ServerSocket(9999)) {

            Socket connection = null;

            Scanner scanner = new Scanner(System.in);

            while (true) {

                System.out.println("9999服务器");

                String next = scanner.next();

                System.out.println("next = " + next);

                try {

                    if (connection==null){

                        connection = server.accept();

                    }

                    if ("000".equals(next)){

                        System.out.println("重置连接成功");

                        connection=null;
                        connection = server.accept();
                        continue;

                    }

                    System.out.println("connection = " + connection);

                    Writer out = new OutputStreamWriter(connection.getOutputStream());

                    System.out.println("out = " + out);

                    Date now = new Date();
                    out.write(next + "\r\n");
                    out.flush();
//                    connection.close();
                } catch (IOException ignored) {

                } finally {
                    //                        if (connection != null) connection.close();
                }
            }
        }
    }


}
